package net.begincode.biz.impl;

import net.begincode.blog.bean.vo.BlogBaseInfo;
import net.begincode.bean.HomeTypeWithBlogInfo;
import net.begincode.biz.HomeBiz;
import net.begincode.blog.entity.HomeType;
import net.begincode.blog.entity.HomeTypeBlog;
import net.begincode.blog.enums.HomeTypeFlagEnum;
import net.begincode.blog.service.BlogService;
import net.begincode.blog.service.HomeTypeBlogService;
import net.begincode.blog.service.HomeTypeService;
import net.begincode.common.BlogConstants;
import net.begincode.common.CollectionUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class HomeBizImpl implements HomeBiz {

    @Resource
    private HomeTypeService homeTypeService;
    @Resource
    private HomeTypeBlogService homeTypeBlogService;
    @Resource
    private BlogService blogService;

    @Override
    public List<HomeTypeWithBlogInfo> queryHomeInfo() {
        List<HomeType> homeTypes = homeTypeService.selectByFlag(HomeTypeFlagEnum.EFFECT.getFlagCode());
        return CollectionUtils.safes(homeTypes).stream()
                .map(homeType -> queryHomeTypeBlog(homeType))
                .collect(Collectors.toList());
    }

    private HomeTypeWithBlogInfo queryHomeTypeBlog(HomeType homeType) {
        List<HomeTypeBlog> homeTypeBlogs = homeTypeBlogService.selectByHomeType(homeType.getId(), BlogConstants.HOME_TYPE_SHOW_COUNT);
        List<Long> blogIds = CollectionUtils.safes(homeTypeBlogs).stream().map(HomeTypeBlog::getBlogId).collect(Collectors.toList());
        List<BlogBaseInfo> blogBaseInfos = queryBlogBaseByIds(blogIds);
        HomeTypeWithBlogInfo homeTypeWithBlogInfo = new HomeTypeWithBlogInfo();
        homeTypeWithBlogInfo.setBlogBaseInfos(blogBaseInfos);
        homeTypeWithBlogInfo.setHomeTypeId(homeType.getId());
        homeTypeWithBlogInfo.setHomeTypeName(homeType.getTypeName());
        homeTypeWithBlogInfo.setPriority(homeType.getPriority());
        homeTypeWithBlogInfo.setIcon(homeType.getIcon());
        return homeTypeWithBlogInfo;
    }

    private List<BlogBaseInfo> queryBlogBaseByIds(List<Long> blogIds) {
        return blogService.selectEffectByIds(blogIds);
    }
}
